import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

        String jdbcUrl = "jdbc:mysql://113.44.148.207:3306/linux_exam";
        String jdbcUsername = "root";
        String jdbcPassword = "1qaz@WSX#EDC";

        try (Connection conn = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM t_book");
             ResultSet rs = stmt.executeQuery()) {

            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.append("[");

            while (rs.next()) {
                if (jsonBuilder.length() > 1) {
                    jsonBuilder.append(",");
                }
                jsonBuilder.append("{")
                        .append("\"number\":\"").append(rs.getString("number")).append("\",")
                        .append("\"name\":\"").append(rs.getString("name")).append("\",")
                        .append("\"author\":\"").append(rs.getString("author")).append("\"")
                        .append("}");
            }

            jsonBuilder.append("]");
            response.getWriter().write(jsonBuilder.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("[]");
        }
    }
}

